import aiofiles
from typing_extensions import Literal

from WebBackend.utils import mylog


async def write_file_async(filepath: str, value: str | list[str], write_type: Literal['w', 'w+', 'a', 'a+'] = 'w'):
    try:
        mylog.info(f'[#3b1c]Writing file:{filepath}')
        async with aiofiles.open(filepath, mode=write_type, encoding='utf-8') as f:
            await  f.write(value)
    except Exception as e:
        print(e)
        return False


def write_file_sync(filepath: str, value: str | list[str], write_type: str = 'w'):
    try:
        mylog.info(f'[#3d01]Writing file:{filepath}')
        with open(filepath, write_type) as f:
            if type(value) is str:
                f.write(value)
            elif type(value) is list:
                f.writelines(value)
            else:
                raise TypeError
            f.close()
        return True
    except Exception as e:
        print(e)
